package com.tonghe.job;

import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.entity.Article;
import com.tonghe.service.ArticleService;
import com.tonghe.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Date:2022/5/9- 05- 09- 15:51
 * @Description: 定时任务 - 更新文章浏览量
 **/
@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    /**
    * @description: 获取 redis 中关于浏览量的数据，更新到数据库中
    * @author: TongHe
    * @date: 2022/8/14 19:07
    */

    @Scheduled(cron = "0/30 * * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.REDIS_VIEW_COUNT);

        List<Article> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());
        //更新到数据库中
        articleService.updateBatchById(articles);

    }
}
